import pygame
import sys
import random

# 初始化pygame
pygame.init()

# 游戏配置
BOARD_SIZE = 15  # 棋盘大小
CELL_SIZE = 40   # 每个格子的像素大小
MARGIN = 50      # 棋盘边缘空白
BOARD_COLOR = (220, 179, 92)  # 棋盘颜色
LINE_COLOR = (0, 0, 0)        # 线条颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# 计算窗口大小
WINDOW_WIDTH = BOARD_SIZE * CELL_SIZE + 2 * MARGIN
WINDOW_HEIGHT = BOARD_SIZE * CELL_SIZE + 2 * MARGIN

# 创建窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("五子棋游戏")

# 棋盘状态，0表示空，1表示黑子，2表示白子
board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
current_player = 1  # 1为玩家(黑子)，2为AI(白子)
game_over = False
winner = 0

def draw_board():
    """绘制棋盘"""
    screen.fill(BOARD_COLOR)
    
    # 重新计算 CELL_SIZE 和 MARGIN 以适应当前窗口大小
    global CELL_SIZE, MARGIN
    window_width, window_height = screen.get_size()
    CELL_SIZE = min((window_width - 100) // BOARD_SIZE, (window_height - 100) // BOARD_SIZE)
    CELL_SIZE = max(20, CELL_SIZE)  # 设置最小格子大小
    MARGIN = max(30, (window_width - BOARD_SIZE * CELL_SIZE) // 2)
    
    # 绘制网格线
    for i in range(BOARD_SIZE):
        # 垂直线
        pygame.draw.line(screen, LINE_COLOR, 
                         (MARGIN + i * CELL_SIZE, MARGIN),
                         (MARGIN + i * CELL_SIZE, MARGIN + (BOARD_SIZE - 1) * CELL_SIZE))
        # 水平线
        pygame.draw.line(screen, LINE_COLOR,
                         (MARGIN, MARGIN + i * CELL_SIZE),
                         (MARGIN + (BOARD_SIZE - 1) * CELL_SIZE, MARGIN + i * CELL_SIZE))
    
    # 绘制天元和星位
    center_positions = [
        (7, 7),  # 天元
        (3, 3), (3, 11), (11, 3), (11, 11),  # 星位
        (3, 7), (7, 3), (7, 11), (11, 7)
    ]
    
    for x, y in center_positions:
        pygame.draw.circle(screen, LINE_COLOR, 
                          (MARGIN + x * CELL_SIZE, MARGIN + y * CELL_SIZE), 5)

def draw_pieces():
    """绘制棋子"""
    for row in range(BOARD_SIZE):
        for col in range(BOARD_SIZE):
            if board[row][col] != 0:
                color = BLACK if board[row][col] == 1 else WHITE
                pygame.draw.circle(screen, color,
                                  (MARGIN + col * CELL_SIZE, MARGIN + row * CELL_SIZE),
                                  CELL_SIZE // 2 - 2)
                # 如果是最后下的子，加一个红点标记
                if row == last_move[0] and col == last_move[1]:
                    pygame.draw.circle(screen, RED,
                                      (MARGIN + col * CELL_SIZE, MARGIN + row * CELL_SIZE),
                                      5)

def draw_game_over():
    """绘制游戏结束信息"""
    if game_over:
        # 获取当前窗口尺寸
        window_width, window_height = screen.get_size()
        # 根据窗口大小调整字体大小
        font_size = max(24, min(48, window_width // 20))
        font_small_size = max(16, min(32, window_width // 30))
        
        font = pygame.font.Font(None, font_size)
        if winner == 1:
            text = font.render("You win！", True, RED)
        elif winner == 2:
            text = font.render("You lose！", True, RED)
        else:
            text = font.render("TIe！", True, RED)
        
        text_rect = text.get_rect(center=(window_width//2, min(30, window_height//10)))
        screen.blit(text, text_rect)
        
        # 提示重新开始
        font_small = pygame.font.Font(None, font_small_size)
        text_restart = font_small.render("按R重新开始，按Q退出", True, BLACK)
        text_rect_restart = text_restart.get_rect(center=(window_width//2, min(70, window_height//10 + 40)))
        screen.blit(text_restart, text_rect_restart)

def check_win(row, col, player):
    """检查是否获胜"""
    directions = [
        [(0, 1), (0, -1)],   # 水平
        [(1, 0), (-1, 0)],   # 垂直
        [(1, 1), (-1, -1)],  # 主对角线
        [(1, -1), (-1, 1)]   # 副对角线
    ]
    
    for direction in directions:
        count = 1  # 包含当前棋子
        # 向一个方向检查
        for dx, dy in direction:
            x, y = row + dx, col + dy
            while 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE and board[x][y] == player:
                count += 1
                x, y = x + dx, y + dy
        
        if count >= 5:
            return True
    return False

def is_board_full():
    """检查棋盘是否已满"""
    for row in board:
        if 0 in row:
            return False
    return True

def ai_move():
    """AI下棋"""
    global current_player, game_over, winner, last_move
    
    # 简单AI策略：
    # 1. 检查AI是否能获胜
    # 2. 检查是否需要阻止玩家获胜
    # 3. 随机下棋
    
    # 寻找获胜位置
    for row in range(BOARD_SIZE):
        for col in range(BOARD_SIZE):
            if board[row][col] == 0:
                board[row][col] = 2
                if check_win(row, col, 2):
                    last_move = (row, col)
                    if check_win(row, col, 2):
                        game_over = True
                        winner = 2
                    current_player = 1
                    return
                board[row][col] = 0
    
    # 阻止玩家获胜
    for row in range(BOARD_SIZE):
        for col in range(BOARD_SIZE):
            if board[row][col] == 0:
                board[row][col] = 1
                if check_win(row, col, 1):
                    board[row][col] = 2
                    last_move = (row, col)
                    current_player = 1
                    return
                board[row][col] = 0
    
    # 随机下棋（但优先选择靠近已有棋子的位置）
    candidates = []
    for row in range(BOARD_SIZE):
        for col in range(BOARD_SIZE):
            if board[row][col] == 0:
                # 检查周围是否有棋子
                has_neighbor = False
                for dx in [-1, 0, 1]:
                    for dy in [-1, 0, 1]:
                        nx, ny = row + dx, col + dy
                        if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and board[nx][ny] != 0:
                            has_neighbor = True
                            break
                    if has_neighbor:
                        break
                if has_neighbor:
                    candidates.append((row, col))
    
    if candidates:
        row, col = random.choice(candidates)
    else:
        # 如果没有邻居，随机选择一个空位
        empty_positions = [(r, c) for r in range(BOARD_SIZE) for c in range(BOARD_SIZE) if board[r][c] == 0]
        if empty_positions:
            row, col = random.choice(empty_positions)
        else:
            return  # 棋盘已满
    
    board[row][col] = 2
    last_move = (row, col)
    
    # 检查AI是否获胜
    if check_win(row, col, 2):
        game_over = True
        winner = 2
    
    # 检查是否平局
    if is_board_full():
        game_over = True
    
    current_player = 1

def reset_game():
    """重置游戏"""
    global board, current_player, game_over, winner, last_move
    board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
    current_player = 1
    game_over = False
    winner = 0
    last_move = (-1, -1)

# 记录最后一步的位置
last_move = (-1, -1)

# 游戏主循环
clock = pygame.time.Clock()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:  # 按R重新开始
                reset_game()
            if event.key == pygame.K_q:  # 按Q退出
                pygame.quit()
                sys.exit()
        
        # 处理窗口大小调整事件
        if event.type == pygame.VIDEORESIZE:
            # 确保窗口有最小尺寸
            new_width = max(400, event.w)
            new_height = max(400, event.h)
            screen = pygame.display.set_mode((new_width, new_height), pygame.RESIZABLE)
        
        if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            if current_player == 1:  # 玩家回合
                x, y = event.pos
                # 转换为棋盘坐标（使用当前的MARGIN和CELL_SIZE）
                col = round((x - MARGIN) / CELL_SIZE)
                row = round((y - MARGIN) / CELL_SIZE)
                
                # 检查坐标是否有效
                if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE:
                    if board[row][col] == 0:  # 位置为空
                        board[row][col] = 1
                        last_move = (row, col)
                        
                        # 检查玩家是否获胜
                        if check_win(row, col, 1):
                            game_over = True
                            winner = 1
                        
                        # 检查是否平局
                        if is_board_full():
                            game_over = True
                        
                        # 切换到AI回合
                        if not game_over:
                            current_player = 2
    
    # AI回合
    if current_player == 2 and not game_over:
        pygame.time.wait(500)  # 等待500ms增加真实感
        ai_move()
    
    # 绘制游戏画面
    draw_board()
    draw_pieces()
    draw_game_over()
    
    pygame.display.flip()
    clock.tick(60)